<template>
  <div>
    <el-row>
      <el-col>
        <my-form
          :formOptions="findFormOptions"
          :isInline="true"
          :isSearch="true"
          @sureSubmit="findTableData"
        >
          <template #bottom_button>
            <el-button
              icon="el-icon-refresh"
              size="mini"
              type="primary"
              @click="reset"
              >重置</el-button
            >
          </template>
        </my-form>
      </el-col>
    </el-row>
    <el-row type="flex" justify="end">
      <el-col :span="2">
        <el-popconfirm
          confirm-button-text="审核通过"
          cancel-button-text="审核不通过"
          confirm-button-type="success"
          cancel-button-type="danger"
          @confirm="check_T"
          @cancel="check_F"
          icon="el-icon-info"
          icon-color="red"
          title="请选择操作"
        >
          <el-button
            slot="reference"
            icon="el-icon-coordinate"
            type="primary"
            size="mini"
            v-if="nowRoot != '教师'"
            >批量审核</el-button
          >
        </el-popconfirm>
      </el-col>
      <el-col :span="10">
        <el-button
          size="mini"
          @click="add"
          icon="el-icon-circle-plus"
          type="primary"
          v-if="nowRoot === '教师'"
          >新增</el-button
        >

        <el-upload
          class="upload-demo"
          ref="excelUpload"
          action="http://localhost:8080/api/project/hUploadExcel"
          :before-upload="onBeforeUpload"
          :on-success="uploadSuccess"
          :show-file-list="false"
        >
          <el-button icon="el-icon-upload" type="primary" size="mini" v-if="nowRoot === '教师'"
            >导入数据表格</el-button
          >
        </el-upload>
        <el-button size="mini" icon="el-icon-download" type="primary" @click="downloadExample"
          >下载导入样例xlsx表格</el-button
        >
        <el-button size="mini" icon="el-icon-download" type="primary" @click="downloadExcel"
          >导出表格</el-button
        >
      </el-col>
    </el-row>
    <el-row>
      <el-col>
        <my-table
          :hasBorder="true"
          :hasIndex="true"
          :hasPagination="true"
          :hasStripe="true"
          :hasSelection="true"
          :tableColumnOptions="tableColumnOptions"
          :tableData="tableData"
          @selectionChange="selectionChange"
        >
          <template #hbegin="{ data }">
            {{ (data.hbegin + "").slice(0, 10) }}
          </template>
          <template #hstart="{ data }">
            {{ (data.hstart + "").slice(0, 10) }}
          </template>
          <template #hend="{ data }">
            {{ (data.hend + "").slice(0, 10) }}
          </template>
          <template #hsstate="{ data }">
            {{
              data.hsstate == "-1"
                ? "未通过"
                : data.hsstate == "0"
                ? "未审核"
                : data.hsstate == "1"
                ? "院级通过"
                : "校级通过"
            }}
          </template>
          <template #operation="{ data }">
            <el-button type="text" @click="look(data)">查看</el-button>
            <el-button
              type="text"
              @click="update(data)"
              v-if="nowRoot === '教师'"
              >编辑</el-button
            >
            <el-button
              type="text"
              @click="remove(data)"
              v-if="nowRoot === '教师'"
              >删除</el-button
            >
          </template>
        </my-table>
      </el-col>
    </el-row>
    <my-dialog :dialogVisible.sync="infoDialog" :title="infoTitle">
      <template #content>
        <my-form
          :form="isAddInfo ? copyForm : form"
          :formOptions="infoFormOptions"
          :rules="infoRules"
          @sureSubmit="infoFormSubmit"
          ref="infoForm"
        >
          <template #hadmin="{ data }">
            <el-autocomplete
              v-model="user1"
              :fetch-suggestions="querySearch"
              placeholder="请输入内容"
              @select="handleSelect_person"
              style="width: 165px"
            ></el-autocomplete>
          </template>
          <!-- <template #hcategory>
            <el-select
              v-model="test1"
              placeholder="请选择"
              @change="handleLevel1"
            >
              <el-option
                v-for="item in level1"
                :key="item.hnatsciLevel"
                :label="item.hnatsciLevel"
                :value="item.hnatsciLevel"
              >
              </el-option>
            </el-select>
          </template> -->
          <template #bottom_button>
            <el-upload
              class="upload-files"
              ref="filesUpload"
              action="http://localhost:8080/api/SciThesis/uploadFile"
              :before-upload="onBeforeUploadFile"
              :data="uploadmsg"
              :multiple="true"
              :limit="1"
              :show-file-list="true"
              :auto-upload="false"
            >
              <el-button type="success"icon="el-icon-upload" size="mini"
                >上传附件(仅支持一个文件)</el-button
              >
            </el-upload>
          </template>
        </my-form>
      </template>
    </my-dialog>
    <my-dialog :dialogVisible.sync="lookDialog">
      <template #content>
        <my-description :border="false" :list="list">
          <template #bottom>
            下载附件
            <el-link
              type="primary"
              v-for="(item, index) in files"
              :key="item"
              @click="downLoadFiles(item)"
              >{{ item }}</el-link
            >
          </template>
        </my-description>
      </template>
    </my-dialog>
  </div>
</template>

<script>
import myForm from "@/components/myForm.vue";
import myTable from "@/components/myTable.vue";
import myDialog from "@/components/myDialog.vue";
import myDescription from "@/components/myDescription.vue";
import {getModelByLabel,projectCate,getLabelByModel,contractType,contractStatus,partyACate} from "@/utils/metaInfo"
import {
  A_tableData,
  A_add,
  A_update,
  A_remove,
  A_check_T,
  A_check_F,
  A_downLoadExcel,
  A_getFile,
  // A_getLevel1,
  A_findTableData,
  A_downLoadExample,
} from "@/api/resultMange/researchProjects/crossingProject";
import {
  E_beforeUpload,
  E_uploadSuccess,
  E_downloadExcel,
} from "@/utils/aboutExcel";
import cloneDeep from "lodash/cloneDeep";
import { A_downLoadFile, A_showFile, A_getKey } from "@/utils/aboutFile";
import { A_getUserList } from "@/utils/aboutUsers";
import { mapState } from "vuex";
export default {
  name: "crossingProject",
  inject: ["reload"],
  data() {
    return {
      findFormOptions: [{ type: "input", label: "合同名称", model: "hname" }],
      tableColumnOptions: [
        {
          label: "合同名称",
          prop: "hname",
        },
        {
          label: "合同编号",
          prop: "hnumber",
        },
        {
          label: "学科分类",
          prop: "hpcategory",
        },
        {
          label: "合同类别",
          prop: "hcategory",
        },
        {
          label: "甲方类别",
          prop: "hycategory",
        },
        {
          label: "合同负责人编号",
          prop: "hadmin",
          width: "120",
        },
        {
          label: "合同负责人姓名",
          prop: "name",
          width: "120",
        },
        {
          label: "合同成员",
          prop: "hnum",
        },
        {
          label: "合同状态",
          prop: "hstate",
        },
        {
          label: "合同金额（万元）",
          prop: "hamount",
        },
        {
          isSlot: true,
          slotName: "hbegin",
          label: "合同时间",
          prop: "hbegin",
        },
        {
          isSlot: true,
          slotName: "hstart",
          label: "立项时间",
          prop: "hstart",
        },
        {
          isSlot: true,
          slotName: "hend",
          label: "结项时间",
          prop: "hend",
        },
        {
          label: "甲方公司",
          prop: "hjname",
        },
        {
          label: "甲方城市",
          prop: "hcity",
        },
        {
          label: "业绩分值",
          prop: "hscore",
        },
        {
          isSlot: true,
          slotName: "hsstate",
          label: "审核状态",
          prop: "hsstate",
        },
        {
          label: "操作",
          width: "180",
          isSlot: true,
          slotName: "operation",
          fixed: "right",
        },
      ],
      tableData: [],
      infoDialog: false,
      infoTitle: "编辑操作",
      isAddInfo: false,
      lookDialog: false,
      form: {},
      copyForm: {},
      infoFormOptions: [
        {
          type: "input",
          label: "合同名称",
          model: "hname",
        },
        {
          type: "input",
          label: "合同编号",
          model: "hnumber",
        },
        {
          type: "radio",
          label: "学科分类",
          model: "hpcategory",
          width: 217,
          options: projectCate,
        },
        {
          type: "radio",
          label: "合同类别",
          model: "hcategory",
          options: contractType,
        },
        {
          type: "radio",
          label: "甲方类别",
          model: "hycategory",
          width: 508,
          options: partyACate,
        },
        {
          type: "slot",
          slotName: "hadmin",
          label: "合同负责人编号",
          model: "hadmin",
        },
        {
          type: "input",
          label: "合同成员",
          model: "hnum",
        },
        {
          type: "radio",
          label: "合同状态",
          model: "hstate",
          options: contractStatus,
        },
        {
          type: "input",
          label: "合同金额（万元）",
          model: "hamount",
        },
        {
          type: "date",
          label: "合同时间",
          model: "hbegin",
        },
        {
          type: "date",
          label: "立项时间",
          model: "hstart",
          width: 205,
        },
        {
          type: "date",
          label: "结项时间",
          model: "hend",
        },
        {
          type: "input",
          label: "甲方公司",
          model: "hjname",
        },
        {
          type: "input",
          label: "甲方城市",
          model: "hcity",
          width: 220,
        },
      ],
      infoRules: {
        hpcategory: [{ required: true, message: "请选择学科分类" }],
        hcategory: [{ required: false, message: "请选择合同类别" }],
        hycategory: [{ required: true, message: "请选择甲方类别" }],
        hname: [{ required: true, message: "请输入合同名称" }],
        hnumber: [{ required: true, message: "请输入合同编号" }],
        hadmin: [{ required: true, message: "请输入合同负责人编号" }],
        hnum: [{ required: true, message: "请输入合同成员" }],
        hstate: [{ required: true, message: "请选择合同状态" }],
        hamount: [{ required: true, message: "请输入合同金额（万元）" }],
        hbegin: [{ required: true, message: "请选择合同时间" }],
        hstart: [{ required: true, message: "请选择立项时间" }],
        hend: [{ required: true, message: "请选择结项时间" }],
        hjname: [{ required: true, message: "请输入甲方公司" }],
        hcity: [{ required: true, message: "请输入甲方城市" }],
      },
      multipleSelection: [],
      uploadmsg: {},
      files: [],
      level1: [],
      user1: "asdasdasda",
      user_list: null,
      fileKey: 0,
    };
  },
  components: {
    myForm,
    myTable,
    myDialog,
    myDescription,
  },
  created() {
    this.getTableData();
    this.getUserList()
    // this.getLevel1();
  },
  watch:{
    "form.hpcategory" :{
      // 此处监听variable变量，当期有变化时执行
				handler(item1,item2){
					// item1为新值，item2为旧值
          console.log(item1,item2)
				}
    }
  },
  methods: {
     async getUserList() {
      let result = await A_getUserList();
      result.forEach((item) => {
        const value=item.userId+' : '+item.userName
        item.value=value
      });
      this.user_list=result
      // console.log(this.user_list)
    },
    async findTableData(data) {
      let result = await A_findTableData(data);
      this.tableData = cloneDeep(result.data);
      if (result.code === 1) {
        this.tableData = cloneDeep(result.data);
      } else {
        this.$message({ type: "error", message: "信息获取失败" });
      }
    },
    async getTableData() {
      let result = await A_tableData({});
      
      if (result.code === 1) {
        this.tableData = cloneDeep(result.data);
        this.tableData.forEach(item=>{
          item.hpcategory = getLabelByModel(item.hpcategory,projectCate)
          item.hcategory = getLabelByModel(item.hcategory,contractType)
          item.hstate = getLabelByModel(item.hstate,contractStatus)
          item.hycategory = getLabelByModel(parseInt(item.hycategory),partyACate)
        })
        // console.log(this.tableData)
      } else {
        this.$message({ type: "error", message: "信息获取失败" });
      }
    },
    async reset() {
      let result = await A_tableData({});
     
      if (result.code === 1) {
        this.tableData = cloneDeep(result.data);
      } else {
        this.$message({ type: "error", message: "信息获取失败" });
      }
    },
    selectionChange(data) {
      this.multipleSelection = cloneDeep(data);
    },
    async look(data) {
      this.form = cloneDeep(data);
      this.lookDialog = true;
      const { hkey } = data;
      let res = await A_getFile(hkey);
      if (res.code === 1) {
        this.files = res.data;
      } else {
        this.$message({ type: "error", message: "出错啦" });
      }
    },
    add() {
      this.isAddInfo = true;
      this.infoDialog = true;
      this.getUserList();
    },
    update(data) {
      this.isAddInfo = false;
      this.infoDialog = true;
      for (let cate of this.user_list) {
        if (cate.userId === data.hadmin) {
          this.user1 = cate.value;
        }
      }
      this.form = cloneDeep(data);
      this.getUserList();
    },
    remove(data) {
      this.$confirm("你确定要删除该数据吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const { hkey } = data;
          let res = await A_remove(hkey);
          if (res.code === 1) {
            this.$message({ type: "success", message: res.data });
            this.reload();
          } else {
            this.$message({ type: "error", message: res.msg });
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    async check_T() {
      if (this.multipleSelection.length > 0) {
        let res = await A_check_T(this.downloadExcelData);
        if (res.code === 1) {
          this.$message({ type: "success", message: res.data });
          this.reload();
        } else {
          this.$message({ type: "error", message: res.msg });
        }
      } else {
        this.$message.warning("请选择数据");
      }
    },
    async check_F() {
      if (this.multipleSelection.length > 0) {
        let res = await A_check_F(this.downloadExcelData);
        if (res.code === 1) {
          this.$message({ type: "success", message: res.data });
          this.reload();
        } else {
          this.$message({ type: "error", message: res.msg });
        }
      } else {
        this.$message.warning("请选择数据");
      }
    },
    async infoFormSubmit(data) {
      data.hpcategory = getModelByLabel(data.hpcategory,projectCate)
      data.hcategory = getModelByLabel(data.hcategory,contractType)
      data.hstate = getModelByLabel(data.hstate,contractStatus)
      data.hycategory = getModelByLabel(data.hycategory,partyACate)
      if (this.isAddInfo) {
        let res = await A_add(data);
        if (res.code === 1) {
          await this.getFileKey();
          await this.$refs.filesUpload.submit();
          this.$message({ type: "success", message: res.data });
          this.reload();
        } else {
          this.$message({ type: "error", message: res.msg });
        }
      } else {
        let res = await A_update(data);
        if (res.code === 1) {
          await this.$refs.filesUpload.submit();
          this.$message({ type: "success", message: res.data });

          this.reload();
        } else {
          this.$message({ type: "error", message: res.msg });
        }
      }
    },
    onBeforeUpload(file) {
      return E_beforeUpload(file);
    },
    uploadSuccess(res, file, flieist) {
      E_uploadSuccess(res);
      this.reload();
    },
    downloadExcel() {
      if (this.multipleSelection.length > 0) {
        E_downloadExcel(this.downloadExcelData).then(
          () => {
            A_downLoadExcel().then(
              (res) => {
                const url = window.URL.createObjectURL(new Blob([res]));
                const link = document.createElement("a");
                link.href = url;
                link.setAttribute("download", "横向项目.xls");
                document.body.appendChild(link);
                link.click();
              },
              () => {
                this.$message({ type: "error", message: "出错了" });
              }
            );
          },
          () => {
            this.$message({ type: "error", message: "出错了" });
          }
        );
      } else {
        this.$message({ type: "warning", message: "请选择要导出的数据" });
      }
    },
    downloadExample() {
      A_downLoadExample().then(
        (res) => {
          const url = window.URL.createObjectURL(new Blob([res]));
          const link = document.createElement("a");
          link.href = url;
          link.setAttribute("download", "导入数据样例表.xls");
          document.body.appendChild(link);
          link.click();
        },
        () => {
          this.$message({ type: "error", message: "出错了" });
        }
      );
    },
    async onBeforeUploadFile(file) {
      if (this.isAddInfo) {
        this.uploadmsg = {
          articalTcatogory: file.name,
          articalCatogory: 1,
          articalId: this.fileKey,
        };
      } else {
        const { hkey } = this.form;
        this.uploadmsg = {
          articalTcatogory: file.name,
          articalCatogory: 1,
          articalId: hkey,
        };
      }
    },
    async downLoadFiles(file) {
      const { hkey } = this.form;
      let result = await A_downLoadFile(1, hkey, file);
      A_showFile(file, result);
    },
    async getLevel1() {
      let result = await A_getLevel1();
      this.level1 = result.data;
    },
    handleLevel1(item) {
      this.$refs.infoForm.form.hcategory = item;
    },
    async getFileKey() {
      let result = await A_getKey(1);
      this.fileKey = result.data;
    },
    querySearch(queryString, cb) {
      var user_list = this.user_list;
      var results = queryString
        ? user_list.filter(this.createFilter(queryString))
        : user_list;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    createFilter(queryString) {
      return (user_list) => {
        return (
          user_list.userName.indexOf(queryString) === 0
        );
      };
    },
    handleSelect_person(item) {
      this.$refs.infoForm.form.hadmin = item.userId;
    },
  },
  computed: {
    ...mapState("myInfo", ["nowRoot"]),
    downloadExcelData() {
      let arr = [];
      this.multipleSelection.forEach((item) => {
        arr.push(item.hkey);
      });
      return arr;
    },
    list() {
      const {
        hname,
        hnumber,
        hpcategory,
        hcategory,
        hycategory,
        hadmin,
        hnum,
        hstate,
        hamount,
        hbegin,
        hstart,
        hend,
        hjname,
        hcity,
        hscore,
        hsstate,
      } = this.form;
      return [
        {
          label: "合同名称",
          value: hname,
        },
        {
          label: "合同编号",
          value: hnumber,
        },
        {
          label: "学科分类",
          value: hpcategory,
        },
        {
          label: "合同类别",
          value: hcategory,
        },
        {
          label: "甲方类别",
          value: hycategory,
        },
        {
          label: "合同负责人编号",
          value: hadmin,
        },
        {
          label: "合同成员",
          value: hnum,
        },
        {
          label: "合同状态",
          value: hstate,
        },
        {
          label: "合同金额（万元）",
          value: hamount,
        },
        {
          label: "合同时间",
          value: (hbegin + "").slice(0, 10),
        },
        {
          label: "立项时间",
          value: hstart,
        },
        {
          label: "结项时间",
          value: hend,
        },
        {
          label: "甲方公司",
          value: hjname,
        },
        {
          label: "甲方城市",
          value: hcity,
        },
        {
          label: "科研分值",
          value: hscore,
        },
        {
          label: "审核状态",
          value: hsstate,
        },
      ];
    },
  },
};
</script>

<style scoped>
.upload-demo {
  display: inline-block;
  margin: 0 3px;
}
</style>